package bluerain.io.adapter.ui;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bluerain.io.adapter.R;

/**
 * Created by foredawn on 15-9-9.
 * 应用最广泛的SimpleAdapter例子,
 */
public class SimpleAdapterTest extends Activity {

    private String[] names = new String[]{
            "李白", "小明", "旺财"
    };
    private String[] descs = new String[]{
            "小学课本中经常出现的著名诗人",
            "小故事中经常出现的主角名称",
            "电视剧中经常出现的宠物狗昵称"
    };
    private int[] imgs = new int[]{
            R.drawable.li_bai,
            R.drawable.xiao_ming,
            R.drawable.wang_cai
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_listview);
        ListView list = (ListView) findViewById(R.id.simpleList);

        List<Map<String, Object>> items = new ArrayList<>();
        Map<String, Object> item = null;
        for (int i = 0; i < names.length; i++) {
            item = new HashMap<>();
            item.put("header", imgs[i]);
            item.put("name", names[i]);
            item.put("desc", descs[i]);
            items.add(item);
        }

        SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.simple_item,
                new String[]{"header", "name", "desc"},
                new int[]{R.id.header, R.id.name, R.id.desc});

        list.setAdapter(adapter);

        //相关事件
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                show(names[position] + "被单击了.");
            }
        });

        list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                show(names[position] + "被选中了.");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    public void show(String text) {
        Toast.makeText(SimpleAdapterTest.this, text, Toast.LENGTH_SHORT).show();
    }
}
